/*
二分查找法的基本实现

 */


package com.diudiu.BinarySearch;

public class BinarySearch01 {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 6, 7, 9, 11, 24, 56, 66, 77, 88, 99, 121, 234, 345};
        int target = 9;
        int result = myBinarySearch01(array, target);
        System.out.println(result);

    }

    private static int myBinarySearch01(int[] array, int target) {
        //计算数组长度
        int len = array.length;
        //左边指针
        int left = 0;
        //右边指针
        int right = len - 1;
        while (left <= right) {
            //中间变量
            //注：>>>无符号右移，忽略符号位，空位都以0补齐，避免用 / 造成失误
            int mid = (left + right) >>> 1;
            //目标值小于中间值
            if (target < array[mid]) {
                //右指针赋值为中间值减一
                right = mid - 1;
            } else if (target > array[mid]) {
                //左指针赋值为中间值加一
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
